package org.kiwi.data.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by jack on 16/10/24.
 */
public class PropertiesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    public static final String DEFAULT_DB_FILE_PATH = "test.properties";

    public static final String DEFAULT_DB_CONFIG_KEY = "/resource/RDBMS/kiwi-dataSource";

    private static final Properties DB_PROPERTIES = new Properties();

    static {
        InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(DEFAULT_DB_FILE_PATH);
        try {
            DB_PROPERTIES.load(inputStream);
        } catch (IOException e) {
            if (LOGGER.isDebugEnabled()){
                LOGGER.debug("load db config file has some problem.",e);
            }
            throw new IllegalArgumentException("invalid db config file or path");
        }
    }

    public static Properties getDBPropsConfig() {
        return DB_PROPERTIES;
    }

    public static String getDbConfig() {
        return getDbConfig(DEFAULT_DB_CONFIG_KEY);
    }

    public static String getDbConfig(String key) {
        Object dbConfig = DB_PROPERTIES.get(key);

        Assert.notNull(dbConfig, "dbConfig must not be null");
        Assert.hasText(dbConfig.toString(), "dbConfig is required");

        return dbConfig.toString();
    }

}
